<?php
namespace app\api\controller\v1;
use think\admin\Controller;
use think\Response;
use app\data\model\DataDevice;
use app\data\model\DataCatToiletLog;
use app\data\model\DataDeviceLog;
/**
 * 设备数据接口
 * @class Device
 * @package app\api\controller\v1
 *
 */
class Device extends Controller
{
    //获取设备属性
    public function get_property(){
        $id = input('get.id');//设备iotId
        $device = DataDevice::mk()->where(['iotId'=>$id])->find()->toArray();
        $device['prop']=[
            'temperature'=>60,
            'poopBagHeight'=>'20',//集便器高度
            'disinfectantLeft'=>0,//消毒水余量
            'bucketLeft'=>99//猫粮剩余
        ];
        $this->success('获取成功',$device);
    }
    //获取设备如厕次数
    public function get_toilet_times(){
        $id = input('get.id');//设备iotId
        $res['today_times'] = DataCatToiletLog::mk()->where(['iot_id'=>$id])->whereDay('create_at')->count();
        $res['yesterday_times'] = DataCatToiletLog::mk()->where(['iot_id'=>$id])->whereDay('create_at', 'yesterday')->count();
        $compare = $res['today_times'] - $res['yesterday_times'];
        $res['compare'] = $compare;
        if($compare == 0){
            $res['vary'] = 0 ;
        }else if($compare > 0){
            $res['vary'] = 1 ;
        }else{
            $res['vary'] = 2 ;
        }
        //平均时长duration
        $res['today_avg'] = DataCatToiletLog::mk()->where(['iot_id'=>$id])->whereDay('create_at')->avg('duration');
        $res['yesterday_avg'] = DataCatToiletLog::mk()->where(['iot_id'=>$id])->whereDay('create_at', 'yesterday')->avg('duration');
        $compare_avg = $res['today_avg'] - $res['yesterday_avg'];
        $res['compare_avg'] = $compare_avg;
        if($compare_avg == 0){
            $res['vary_avg'] = 0 ;
        }else if($compare_avg > 0){
            $res['vary_avg'] = 1 ;
        }else{
            $res['vary_avg'] = 2 ;
        }

        $this->success('获取成功',$res);
    }
    //今日设备日志
    public function get_today_work_log(){
        $id = input('get.id');
        $res = DataDeviceLog::mk()->alias('l')->field('l.*,c.nickname,c.avatar,date_format(l.create_at, "%m-%d") as day,date_format(l.create_at, "%h:%m") as time')
            ->leftjoin('data_cat c','c.id = l.cat_id')
            ->where(['l.iot_id'=>$id])->whereDay('l.create_at')
            ->paginate(10)->toArray();
        $this->success('获取成功',$res);
    }
    //我的设备
    public function my()
    {
        $res = DataDevice::mk()->my($this->request->uid);
        $this->success('获取成功',$res);
    }
    //设置物属性
    public function set_pro()
    {
        $this->success('设置成功',[]);
    }
    //设置物事件
    public function set_event()
    {
        $this->success('设置成功',[]);
    }
    //设置物服务
    public function set_service()
    {
        $this->success('设置成功',[]);
    }
}
